package com.hunttown.common.domain;

import java.io.Serializable;
import java.util.Collections;
import java.util.List;

public class Page<T> implements Serializable {
    private int pn;
    private int start;
    private int pageSize;
    private int totalPages;
    private long totalItems;
    private List<T> items;

    private Page(int pn, int pageSize, List<T> items) {
        if (pn < 1) {
            pn = 1;
        }

        this.pn = pn;
        if (pageSize < 5) {
            pageSize = 5;
        }

        if (pageSize > 10000) {
            pageSize = 10000;
        }

        this.pageSize = pageSize;
        this.start = (this.pn - 1) * this.pageSize;
        this.items = items;
    }

    public static Page from(int pn) {
        return new Page(pn, 20, Collections.EMPTY_LIST);
    }

    public static Page from(int pn, int pageSize) {
        return new Page(pn, pageSize, Collections.EMPTY_LIST);
    }

    public static <T> Page from(int pn, int pageSize, List<T> items) {
        return new Page(pn, pageSize, items);
    }

    public static Page from(Query query) {
        return new Page(query.getPn(), query.getPageSize(), Collections.EMPTY_LIST);
    }

    public static <T> Page from(Query query, List<T> items) {
        return new Page(query.getPn(), query.getPageSize(), items);
    }

    public void setItems(List<T> items) {
        this.items = items;
    }

    public void setTotalItems(long totalItems) {
        this.totalItems = totalItems;
        this.totalPages = (int) Math.ceil(1.0D * (double) this.totalItems / (double) this.pageSize);
    }

    public int getPn() {
        return this.pn;
    }

    public int getPageSize() {
        return this.pageSize;
    }

    public int getStart() {
        return this.start;
    }

    public long getTotalItems() {
        return this.totalItems;
    }

    public int getTotalPages() {
        return this.totalPages;
    }

    public List<T> getItems() {
        return this.items;
    }

    public boolean isFirst() {
        return this.pn == 1;
    }

    public boolean isLast() {
        return this.pn == this.totalPages;
    }

    public boolean hasPrevious() {
        return this.pn > 1;
    }

    public boolean hasNext() {
        return this.pn < this.totalPages;
    }
}
